package com.zjj.shiro.authroization.realm;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.zjj.shiro.authroization.permission.MyCustomPermission;
import com.zjj.shiro.authroization.util.CommonUtil;
import com.zjj.shiro.authroization.util.MyCustomAuthenticationInfo;

public class MyRealm extends AuthorizingRealm {
	
	@Override
	public String getName() {
		return "MyRealm";
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName = (String) token.getPrincipal();
		String password = new String((char[]) token.getCredentials());
		if (!"zjj".equals(userName)) {
			throw new AuthenticationException("用户名或密码不正确！");
		}
		if (!"123".equals(password)) {
			throw new AuthenticationException("用户名或密码不正确！");
		}
		
		String userId = "";
		if ("zjj".equals(userName)) {
			userId = "1";
		}
		MyCustomAuthenticationInfo authenticationInfo = new MyCustomAuthenticationInfo(userId, password, getName());
		authenticationInfo.setLoginName(userName);
		return authenticationInfo;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userId = (String) principals.getPrimaryPrincipal();
		AuthorizationInfo  authorizationInfo = setAuthorizationInfo(userId);
		return authorizationInfo;
	}
	
	/**
	 * 设置授权
	 * @param userId
	 * @return
	 */
	private AuthorizationInfo setAuthorizationInfo(String userId) {
		Set<String> roles = new HashSet<String>();
		
		roles = CommonUtil.getUserRoles(userId);
		
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		// 设置角色
		authorizationInfo.setRoles(roles);
		Set<String> availableResources = CommonUtil.getRolesResource();
		
		// 设置资源权限
		authorizationInfo.addObjectPermission(new MyCustomPermission(availableResources));
		return authorizationInfo;
	}
	
}
